/**
 * @description 配置管理
 * @date 2025.5.12
 * @author wz
 * @midify 2025.5.12
 * @editor wz
 */
import { _decorator, BufferAsset } from 'cc';
import ByteBuf from "../../../config/bright/serialization/ByteBuf";
import { Singleton } from '../../utils/Singleton';
import { resMgr } from '../res/ResMgr';
import { Tables } from '../../../config/code/schema';

export default class ConfigMgr extends Singleton {
    public tables: Tables = null;
    private _fileNames: string[] = [];
    private _dataMap = new Map<string, Uint8Array>();
    private _callback: (progress: number, finish: boolean) => void;
    private _progress: number = 0;
    async loadConfig(callback: (progress: number, finish: boolean) => void) {
        this._callback = callback;
        this._progress = 0;
        this._fileNames = Tables.getTableNames();
        let promises: Promise<void>[] = [];
        for (let i = 0; i < this._fileNames.length; i++) {
            promises.push(this._load(this._fileNames[i]))
        }
        await Promise.all(promises);
        this.tables = new Tables(this.getFileData.bind(this));
        this._callback && this._callback(1, true);
    }

    private async _load(fileName: string) {
        const data = await resMgr.load(`data/${fileName}`, BufferAsset, 'config')
        this._dataMap.set(fileName, new Uint8Array(data.buffer().slice(0, data.buffer().byteLength)));
        this._callback && this._callback(++this._progress / this._fileNames.length, false);
    }

    private getFileData(fileName: string): ByteBuf {
        if (this._dataMap.has(fileName)) {
            return new ByteBuf(this._dataMap.get(fileName));
        }
        return null;
    }
}

export const configMgr = ConfigMgr.getInstance<ConfigMgr>();    